package com.ideaaedi.mybatis.data.security.interceptor;

import com.ideaaedi.mybatis.data.security.support.EncryptInfoHolder;
import com.ideaaedi.mybatis.data.security.support.EncryptParser;
import org.apache.ibatis.cache.CacheKey;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.plugin.Intercepts;
import org.apache.ibatis.plugin.Invocation;
import org.apache.ibatis.plugin.Plugin;
import org.apache.ibatis.plugin.Signature;
import org.apache.ibatis.session.ResultHandler;
import org.apache.ibatis.session.RowBounds;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Properties;

/**
 * 自定义Mybatis插件 - 实现数据库(入库/出库)敏感字段脱敏
 *
 * @author JustryDeng
 * @since 2021/2/10 22:40:59
 */
@Intercepts(value = {
        // 入
        @Signature(type = Executor.class, method = "update", args = {MappedStatement.class, Object.class}),
        // 出
        @Signature(type = Executor.class, method = "query", args = {MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class}),
        @Signature(type = Executor.class, method = "query", args = {MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class, CacheKey.class, BoundSql.class})
})

public class MybatisEncryptPlugin implements Interceptor {
    
    private static final Logger log = LoggerFactory.getLogger(MybatisEncryptPlugin.class);
    
    private final EncryptParser encryptParser;
    
    public MybatisEncryptPlugin(EncryptParser encryptParser) {
        this.encryptParser = encryptParser;
    }
    
    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        Object target = invocation.getTarget();
        if (target instanceof Executor) {
            MappedStatement mappedStatement = (MappedStatement) invocation.getArgs()[0];
            EncryptInfoHolder encryptInfoHolder = encryptParser.determineEncryptInfoHolder(mappedStatement);
            String mappedStatementId = mappedStatement.getId();
            // mybatis-plus的分页count
            if(encryptInfoHolder == null && mappedStatementId.endsWith("_mpCount")) {
                String rawMappedStatementId = mappedStatementId.substring(0, mappedStatementId.length() - "_mpCount".length());
                encryptInfoHolder = encryptParser.determineEncryptInfoHolder(rawMappedStatementId);
                if (encryptInfoHolder != null) {
                    EncryptParser.EncryptOop encryptOop = encryptParser.getEncryptOop();
                    if (!encryptOop.existMpCount(rawMappedStatementId)) {
                        encryptOop.putMpCount(rawMappedStatementId, mappedStatementId);
                    }
                }
            }
            if (encryptInfoHolder == null) {
                log.debug("mappedStatementId [{}] match non-encryptInfoHolder. Operate database directly.", mappedStatementId);
                return invocation.proceed();
            }
            if (encryptInfoHolder.isNeedEncrypt()) {
                // 加密
                log.debug("mappedStatementId [{}] need encrypt.", mappedStatementId);
                Object rowParameter = invocation.getArgs()[1];
                invocation.getArgs()[1] = encryptParser.doEncrypt(mappedStatement, rowParameter, encryptInfoHolder);
            }
            Object rowResult = invocation.proceed();
            if (encryptInfoHolder.isNeedDecrypt()) {
                // 解密
                log.debug("mappedStatementId [{}] need decrypt.", mappedStatementId);
                rowResult = encryptParser.doDecrypt(mappedStatement, rowResult, encryptInfoHolder);
            }
           return rowResult;
        } else {
            throw new UnsupportedOperationException("Base 'MybatisEncryptPlugin.plugin' Setting, curr plugin only support Executor.class");
        }
    }

    @Override
    public Object plugin(Object target) {
        // 因为上面@Signature指定了插件生效范围,即：type为Executor.class StatementHandler.class所以这里只处理这些case就行了
        if (target instanceof Executor) {
            return Plugin.wrap(target, this);
        }
        return target;
    }

    @Override
    public void setProperties(Properties properties) {
        // ignore
    }
}
